package util;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.XMLFilterImpl;

import java.util.HashMap;

public class MyXMLWriter extends XMLFilterImpl
{
    private HashMap <String, String> uriPrefixMap = new HashMap <>();
    private String defaultNameSpace;

    public MyXMLWriter(String defaultNameSpace)
    {
        this.defaultNameSpace = defaultNameSpace;
    }

    @Override
    public void startPrefixMapping(String prefix, String uri) throws SAXException
    {
        uriPrefixMap.put(uri, prefix);
        if (uri.equals(defaultNameSpace))
        {
            prefix = "";
        }
        super.startPrefixMapping(prefix, uri);
    }

    @Override
    public void endPrefixMapping(String prefix) throws SAXException
    {
        super.endPrefixMapping(prefix);
    }

    @Override
    public void startDocument() throws SAXException
    {
        super.startDocument();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException
    {
        String prefix = uriPrefixMap.get(uri);
        if (prefix != null)
        {
            String spaceUrl = prefix + ":";
            if (qName.startsWith(spaceUrl))
            {
                qName = qName.replace(spaceUrl, "");
            }
        }
        super.startElement(uri, localName, qName, atts);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException
    {
        String prefix = uriPrefixMap.get(uri);
        if (prefix != null)
        {
            String spaceUrl = prefix + ":";
            if (qName.startsWith(spaceUrl))
            {
                qName = qName.replace(spaceUrl, "");
            }
        }
        super.endElement(uri, localName, qName);
    }

    @Override
    public void endDocument() throws SAXException
    {
        super.endDocument();
    }
}
